package com.itheima.dianming.util;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
@Slf4j
public class Cmder {

    public static void killPid(Integer pid) throws IOException {
        String s3 = executeCmdCommand("cmd /C taskkill /F /PID " + pid);
        log.info(s3);
    }

    public static Integer getPid(String commend) throws IOException {
        String s = Cmder.executeCmdCommand("cmd /C tasklist |findstr "+commend);
        String[] split = s.split("\\D+");
        for (String s1 : split) {
            if(NumberUtil.isNumber(s1)){
                return Integer.parseInt(s1);
            }
        }
        return null;
    }

    public static Integer getPid(Integer port) throws IOException {
        String s = Cmder.executeCmdCommand("cmd /C netstat -ano|findstr "+port);
        String[] split = s.split("\n\b");
        for (String s1 : split) {
            if(s1.contains("0.0.0.0:"+port)){
                String pid=s1.replaceAll(".*[^\\d](?=(\\d+))","");
                return Integer.parseInt(pid);
            }
        }
        return null;
    }

    public static boolean findPort(Integer port) throws IOException {
        String s1 = executeCmdCommand("cmd /C netstat -ano|findstr "+port);
        String[] split = s1.split("\n\b");
        for (String s2 : split) {
            if(s2.contains("0.0.0.0:"+port)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(findPort(8080));
        String s = null;
        try {
            // s = executeCmdCommand("cmd /C C: &  cd C:\\Temp &  mvn package");
            //executeCmdCommand("cmd /C C: &  cd C:\\Temp\\target & java -jar reggie.jar");
            String s1 = executeCmdCommand("cmd /C netstat -ano|findstr 8080");
            System.out.println(s1);
            String[] split = s1.split("\n\b");
            for (String s2 : split) {
                if(s2.contains("0.0.0.0:8080")){
                    System.out.println(s2);
                    String str2=s2.replaceAll(".*[^\\d](?=(\\d+))","");
                    System.out.println(str2);
                    //String s3 = executeCmdCommand("cmd /C taskkill /F /PID " + str2);
                    //System.out.println(s3);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(s);
    }
    /**
     * 执行一个cmd命令
     *
     * @param cmdCommand cmd命令
     * @return 命令执行结果字符串，如出现异常返回null
     */
    public static String executeCmdCommand(String cmdCommand) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        Process process = null;
        process = Runtime.getRuntime().exec(cmdCommand);
        int available = process.getInputStream().available();
        System.out.println(available);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n\b");
        }
        System.out.println(stringBuilder.toString());
        return stringBuilder.toString();

    }
    /**
     * 执行bat文件，
     *
     * @param file          bat文件路径
     * @param isCloseWindow 执行完毕后是否关闭cmd窗口
     * @return bat文件输出log
     */
    public static String executeBatFile(String file, boolean isCloseWindow) {
        String cmdCommand = null;
        if (isCloseWindow) {
            cmdCommand = "cmd.exe /c " + file;
        } else {
            cmdCommand = "cmd.exe /k " + file;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行bat文件,新开窗口
     *
     * @param file          bat文件路径
     * @param isCloseWindow 执行完毕后是否关闭cmd窗口
     * @return bat文件输出log
     */
    public static String executeBatFileWithNewWindow(String file, boolean isCloseWindow) {
        String cmdCommand;
        if (isCloseWindow) {
            cmdCommand = "cmd.exe /c start" + file;
        } else {
            cmdCommand = "cmd.exe /k start" + file;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Process process;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行bat脚本
     *
     * @param batScript 脚本内容
     * @param location  脚本存储路径
     * @return 结果
     */
    public static String executeBatScript(String batScript, String location) {
        StringBuilder stringBuilder = new StringBuilder();
        FileWriter fw = null;
        try {
            //生成bat文件
            fw = new FileWriter(location);
            fw.write(batScript);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Process process;
        try {
            process = Runtime.getRuntime().exec(location);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行脚本,不停止,并输出执行结果
     *
     * @param batScript 脚本内容
     * @param location  bat文件生成地址
     */
    public void executeBatScriptAlways(String batScript, String location) {
        FileWriter fw = null;
        try {
            //生成bat文件
            fw = new FileWriter(location);
            fw.write(batScript);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        //运行bat文件
        Process process;
        try {
            process = Runtime.getRuntime().exec(location);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
